import { HealthCheckWithScreenTask, V3proLastErrCache } from "./health.check.class";
import { PanelGroupKey, V3proSubjectMessage } from "../model/v3pro.model";
import { HealthDescEnum, V3proAlertMessageErrTypeEnum } from "../model/v3pro.enum";
import { V3proScreen, V3proScreenAllStatus } from "../../../api/v3pro-api/v3pro.api.response.model";
import { appConfig } from "../../../configs/env.config.load";
import { lensPath, view } from "ramda";
import { V3proAllStatusLambda } from "../helper/v3pro.all.status.lambda.helper";
import { V3proScreenLayoutHelper } from "../helper/v3pro.screen.layout.helper";
import { V3proFileHelper } from "../helper/v3pro.file.helper";
import { V3proScreenImageHelper } from "../helper/v3pro.screen.image.helper";

/**
 * 显示坏点故障
 *
 * 是否支持阈值设置： Y
 * "[0%,100%]
 * 默认20%"	"定时查询
 *
 * 查询周期:
 * 间隔24小时
 *
 * 告警产生的原因:
 * 告警产生的原因 检测到显示像素灯珠开路，单个面板坏点百分比超出阈值
 *
 * 异常现象:
 * 面板中有显示像素不能点亮
 *
 * 维修建议:
 * 更换面板
 *
 * 告警级别: 重要
 */
const errCache = new V3proLastErrCache<PanelGroupKey>();
export class V3proCheckDeadPixelTask extends HealthCheckWithScreenTask<any> {
  async checkResult(
    keyParams: PanelGroupKey[],
    screenId: string,
    allStatus: V3proScreenAllStatus,
    screenLayoutHelper: V3proScreenLayoutHelper,
  ): Promise<V3proSubjectMessage> {
    const message = new V3proSubjectMessage();
    if (!keyParams.length) return message;
    message.setErrStatus();
    keyParams.forEach((group) =>
      group.panels.forEach((panel) => {
        screenLayoutHelper.setPanelErrById(group.id, panel.index);
      }),
    );
    message.files = [
      await V3proFileHelper.panelGroupKey2File(keyParams),
      await new V3proScreenImageHelper(screenLayoutHelper, ["panel"])
        .draw()
        .export2AlertMessageFile(),
    ];
    return message;
  }

  async genKeyParams(
    allStatus: V3proScreenAllStatus,
    screen: V3proScreen,
    screenLayoutHelper: V3proScreenLayoutHelper,
  ): Promise<any> {
    const lens = lensPath(["healthDesc", "description"]);
    const [errs, normals] = V3proAllStatusLambda.filterPanelsWithRemove(allStatus, (panel) => {
      return view(lens, panel).includes(HealthDescEnum.BAD_PIXEL_ALARM);
    });
    return errCache.mergeCache(errs, normals, screen.id, (s) => s.id);
  }

  genSRMqttTopic(
    message: V3proSubjectMessage,
    screenId: string,
    allStatus: V3proScreenAllStatus,
  ): string {
    return `notify/alert/ssads/device-led-disp:dead-pixels/${screenId}`;
  }

  getV3proAlertMessage(): V3proAlertMessageErrTypeEnum {
    return V3proAlertMessageErrTypeEnum.DEAD_PIXEL;
  }

  isNeedUploadFile(
    message: V3proSubjectMessage,
    screenId: string,
    allStatus: V3proScreenAllStatus,
  ): boolean {
    return message.isErrStatus();
  }

  isReportEnabled(keyParams: any, screenId: string): boolean {
    return appConfig.v3pro.errEnable.scanBoardDeadPixel;
  }

  getInterval(): number {
    return appConfig.v3pro.collectTimer.deadPixel * 1000;
  }
}
